package com.ly.demo.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.ly.demo.entity.ParamDTO;
import com.ly.demo.entity.PluginApiEntity;
import okhttp3.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ApiExecutor {

    private static final OkHttpClient client = new OkHttpClient();

    public static String executeApi(PluginApiEntity pluginApiEntity) throws IOException {

        HttpUrl.Builder urlBuilder = HttpUrl.parse(pluginApiEntity.getUrl()).newBuilder();

        List<ParamDTO> parameters = pluginApiEntity.getParameters();
        Map<String, List<ParamDTO>> paramMap = parameters.stream().collect(Collectors.groupingBy(ParamDTO::getPosition));

        List<ParamDTO> queryParam = paramMap.get("Query");
        List<ParamDTO> bodyParam = paramMap.get("Body");
        List<ParamDTO> headParam = paramMap.get("Head");

        // 添加查询参数
        if (CollUtil.isNotEmpty(queryParam)) {
            queryParam.forEach(paramDTO -> urlBuilder.addQueryParameter(paramDTO.getName(), paramDTO.getValue()));
        }
        // 创建带有查询参数的最终URL
        String urlWithParams = urlBuilder.build().toString();

        Headers headers = Headers.of();
        // 请求头
        if (CollUtil.isNotEmpty(headParam)) {
            Map<String, String> headsMap = headParam.stream().collect(Collectors.toMap(ParamDTO::getName, ParamDTO::getValue));
            headers = Headers.of(headsMap);
        }

        // 请求体
        RequestBody requestBody = null;
        if (CollUtil.isNotEmpty(bodyParam)) {
            Map<String, String> body = bodyParam.stream().collect(Collectors.toMap(ParamDTO::getName, ParamDTO::getValue));
            // 假设参数以JSON形式序列化在'parameters'字段中
            requestBody = RequestBody.create(MediaType.parse("application/json"), JSONUtil.toJsonStr(body));
        }

        // 构建请求
        Request request = new Request.Builder()
                .url(urlWithParams)
                .headers(headers)
                .method(pluginApiEntity.getMethod(), requestBody)
                .build();
        // 执行请求
        try (Response response = client.newCall(request).execute()) {
            System.out.println(JSONUtil.toJsonStr(response));
            return response.body().string();
        } catch (IOException e) {
            // 异常处理
            e.printStackTrace();
            throw e;
        }
    }

    public static void main(String[] args) {
        PluginApiEntity pluginApiEntity = new PluginApiEntity();
        pluginApiEntity.setUrl("http://www.baidu.com/s?tn=json");
        pluginApiEntity.setMethod("GET");
        ParamDTO paramDTO = new ParamDTO();
        paramDTO.setName("wd");
        paramDTO.setValue("咖啡");
        paramDTO.setPosition("Query");
        pluginApiEntity.setParameters(Arrays.asList(paramDTO));

        try {
            String response = executeApi(pluginApiEntity);
            System.out.println("API响应：" + response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
